//
//  InfoViewController.m
//  first app
//
//  Created by 林 小明 on 14-7-22.
//
//

#import "InfoViewController.h"
#import "FileCenter.h"
#import "DownloadManager.h"
#import "DownloadCell.h"
#import "PlayManager.h"

@interface InfoViewController ()

@end

@implementation InfoViewController

@synthesize msgtitle;
@synthesize playertitle;
@synthesize totaltime;
@synthesize currenttime;
@synthesize playbutton;
@synthesize downloadallbutton;
@synthesize playslider;
@synthesize downloadList;

static NSString* kStorePath = @"mp3";
static long kDownloadButtonTagKey = 100;
static long kPlayButtonTagKey = 200;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [msgtitle setText:[playViewInfos objectForKey:@"chapterTitle"]];
    
    downloadList.delegate = self;
    downloadList.dataSource = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showPlaystatus:) name:@"Notification_Playstatus" object:nil];
    
    PlayManager* player = [PlayManager sharedSingleton];
    if( ![player isInit] )
    {
        [playertitle setText: player.getTitle];
        playslider.maximumValue = [player getDuration];
        playslider.value = [player getCurrentTime];
        
        [totaltime setText:[[NSString alloc] initWithFormat:@"%0.2d:%0.2d", (int)(playslider.maximumValue)/60, (int)(playslider.maximumValue)%60 ]];
        [currenttime setText:[[NSString alloc] initWithFormat:@"%0.2d:%0.2d", (int)(playslider.value)/60, (int)(playslider.value)%60 ]];
        
        // Set the valueChanged target
        [playslider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
        
        if ( [player isPlaying] )
        {
            [playbutton setTitle:@"Stop" forState:UIControlStateNormal];
            
            [sliderTimer invalidate];
            
            sliderTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateSlider) userInfo:nil repeats:YES];
        }
    }
    else
    {
        playslider.value = 0;
    }
    
    /*
    BOOL file_exist = NO;
    for( NSDictionary *info in downloadInfos )
    {
        NSString *url = [info objectForKey:@"url"];
        NSString* filename = [self getFileNameFromURL:url];
        if ( [FileCenter IsFileExistInDocuments:kStorePath fileName:filename] )
        {
            file_exist = YES;
            break;
        }
    }
    
    if( file_exist )
    {
        [downloadallbutton setHidden:YES];
    }
    */
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction) playButton
{
    PlayManager* player = [PlayManager sharedSingleton];
    if( [playbutton.titleLabel.text isEqual:@"Play"] )
    {
        if (![player isPlaying] )
        {
            if( ![player isInit] )
            {
                [self doResume];
                return;
            }
            
            [self doPlay:0];
        }
    }
    else if( [playbutton.titleLabel.text isEqual:@"Stop"] )
    {
        if ( [player isPlaying] )
        {
            [player stopPlay];
            [playbutton setTitle:@"Play" forState:UIControlStateNormal];
        }
    }
}

- (IBAction) downloadAllButton
{
}

- (void) setViewInfo:(NSDictionary*) viewInfo
{
    playViewInfos = viewInfo;
    
    downloadInfos = [[NSMutableArray alloc] init];
    
    for( NSDictionary* dict in [playViewInfos objectForKey:@"sessionList"] )
    {
        [downloadInfos addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                  kStorePath,@"dir",
                                  [dict objectForKey:@"sessionTitle"],@"desc",
                                  [self getFileNameFromURL:[dict objectForKey:@"sessionURL"]],@"name",
                                  [dict objectForKey:@"sessionURL"],@"url",
                                  nil]];
    }
}

- (void) doStop
{
    PlayManager* player = [PlayManager sharedSingleton];

    [player stopPlay];
    [playbutton setTitle:@"Play" forState:UIControlStateNormal];
}

- (void) doResume
{
    PlayManager* player = [PlayManager sharedSingleton];
    
    //[sliderTimer invalidate];
    
    [playslider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
    
    //sliderTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateSlider) userInfo:nil repeats:YES];
    
    [player startPlay];
    
    [playbutton setTitle:@"Stop" forState:UIControlStateNormal];
}

- (void) doPlay:(int)idx
{
    int playIdx = 0;
    PlayManager* player = [PlayManager sharedSingleton];
    
    NSMutableArray* playlist = [[NSMutableArray alloc] initWithCapacity:20];
    int iter = 0;
    int playiter = 0;
    for ( NSDictionary *downloadInfo in downloadInfos )
    {
        NSString* dirpath = [downloadInfo objectForKey:@"dir"];
        NSString* filename = [downloadInfo objectForKey:@"name"];
        
        if ( [FileCenter IsFileExistInDocuments:dirpath fileName:filename] )
        {
            if( idx == iter )
            {
                playIdx = playiter;
            }
            
            [playlist addObject:downloadInfo];
            playiter++;
        }
        
        iter++;
    }
    
    unsigned long cnt = [playlist count];
    if( cnt == 0 )
    {
        return;
    }
    
    [sliderTimer invalidate];
    [player setPlayList:playlist];
    [player startPlay:playIdx];
    
    playslider.value = 0;
    playslider.maximumValue = [player getDuration];
    [playertitle setText:player.getTitle];
    
    [totaltime setText:[[NSString alloc] initWithFormat:@"%0.2d:%0.2d", (int)(playslider.maximumValue)/60, (int)(playslider.maximumValue)%60 ]];
    [currenttime setText:@"00:00"];
    
    // Set the valueChanged target
    [playslider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
    
    sliderTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateSlider) userInfo:nil repeats:YES];
    
    [playbutton setTitle:@"Stop" forState:UIControlStateNormal];
}

- (NSString *) getFileNameFromURL:(NSString*)url
{
    NSArray *array = [url componentsSeparatedByString:@"/"];
    if( [array count] > 1 )
    {
        unsigned long count = [array count];
        return [array objectAtIndex:count-1];
    }
    
    return nil;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)aplayer successfully:(BOOL)flag
{
    if (flag == YES) {
        playslider.value = 0;
        [currenttime setText:@"00:00"];
        [playbutton setTitle:@"Play" forState:UIControlStateNormal];
        NSLog(@"Playback finish." );
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [downloadInfos count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DownloadCell *cell = (DownloadCell*)[tableView
                                   dequeueReusableCellWithIdentifier:@"DownloadCell"];

    NSDictionary *downloadInfo = [downloadInfos objectAtIndex:indexPath.row];
    NSString *downloadURL = [downloadInfo objectForKey:@"url"];
    
    cell.downloadbutton.tag = indexPath.row + kDownloadButtonTagKey;
    [cell.downloadbutton addTarget:self action:@selector(downloadButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

    cell.playbutton.tag = indexPath.row + kPlayButtonTagKey;
    [cell.playbutton addTarget:self action:@selector(playButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.downloadfilename.text = [downloadInfo objectForKey:@"desc"];
    NSString* downloadFileName = [self getFileNameFromURL:downloadURL];
    
    if ( [FileCenter IsFileExistInDocuments:kStorePath fileName:downloadFileName] )
    {
        NSNumber *fileSize = [[NSNumber alloc] initWithDouble:0];
        NSDictionary* fileAttr = [FileCenter GetDocumentsFileAttribute:kStorePath fileName:downloadFileName];
        if( fileAttr != nil )
        {
            fileSize = [fileAttr objectForKey:NSFileSize];
        }
        float ff = [fileSize doubleValue]/1024.0/1024.0;
        cell.downloadprogress.progress = 1.0f;
        [cell.downloadprogessinfo setText:[NSString stringWithFormat:@"%0.2fM/%0.2fM",ff,ff]];
        [cell.downloadbutton setHidden:YES];
        [cell.playbutton setHidden:NO];
        
        PlayManager* player = [PlayManager sharedSingleton];
        if ( [player isPlaying] && [[player getURL] isEqualToString:downloadURL] )
        {
            [cell.playbutton setTitle:@"Stop" forState:UIControlStateNormal];
        }
    }
    else
    {
        cell.downloadprogress.progress = 0.0f;
        [cell.downloadprogessinfo setText:@"0.0M/0.0M"];
    }

    [cell setDownloadURL:[downloadInfo objectForKey:@"url"]];
    [cell startDownloadListen];

    return cell;
}

- (void)updateSlider
{
    // Update the slider about the music time
    playslider.value = [[PlayManager sharedSingleton] getCurrentTime];
    [currenttime setText:[[NSString alloc] initWithFormat:@"%0.2d:%0.2d", (int)(playslider.value)/60, (int)(playslider.value)%60 ]];
}

- (IBAction)sliderChanged:(UISlider *)sender
{
    // Fast skip the music when user scroll the UISlider
    PlayManager* player = [PlayManager sharedSingleton];
    
    [player setCurrentTime:playslider.value];
    [currenttime setText:[[NSString alloc] initWithFormat:@"%0.2d:%0.2d", (int)(playslider.value)/60, (int)(playslider.value)%60 ]];
}

- (void)showPlaystatus:(NSNotification*) aNotification
{
    NSMutableDictionary *playStatusInfo = [aNotification object];

    int play_status = [[playStatusInfo objectForKey:@"status"] intValue];
    
    if( play_status == PlayerStatusPlay )
    {
        PlayManager* player = [PlayManager sharedSingleton];
        
        playslider.value = 0;
        playslider.maximumValue = [player getDuration];
        [playertitle setText:player.getTitle];
        
        [totaltime setText:[[NSString alloc] initWithFormat:@"%0.2d:%0.2d", (int)(playslider.maximumValue)/60, (int)(playslider.maximumValue)%60 ]];
        [currenttime setText:@"00:00"];
        
        [playbutton setTitle:@"Stop" forState:UIControlStateNormal];
    }
    else if( play_status == PlayerStatusResume )
    {
        [playbutton setTitle:@"Stop" forState:UIControlStateNormal];
    }
    else if( play_status == PlayerStatusStop )
    {
        [playbutton setTitle:@"Play" forState:UIControlStateNormal];
    }
}

#pragma mark - button action
-(IBAction)downloadButtonClicked:(id)sender
{
    long idx = ((UIButton *)sender).tag - kDownloadButtonTagKey;
    
    NSDictionary *downloadInfo = [downloadInfos objectAtIndex:idx];
    NSString* downloadURL = [downloadInfo objectForKey:@"url"];
    
    NSString* fileName = [self getFileNameFromURL:downloadURL];
    if( fileName == nil )
    {
        return;
    }
    
    NSLog(@"fileName:%@", fileName);
    
    if ( [((UIButton *)sender).titleLabel.text isEqual:@"Download"] )
    {
        if( ![FileCenter IsFileExistInDocuments:kStorePath fileName:fileName] )
        {
            [[DownloadManager sharedSingleton] downloadUrl:kStorePath fileName:fileName URL:downloadURL];
            [((UIButton *)sender) setTitle:@"Stop" forState:UIControlStateNormal];
        }
    }
    else if ( [((UIButton *)sender).titleLabel.text isEqual:@"Stop"] )
    {
        [[DownloadManager sharedSingleton] stopDownload:downloadURL];
        [((UIButton *)sender) setTitle:@"Download" forState:UIControlStateNormal];
    }
}

#pragma mark - button action
-(IBAction)playButtonClicked:(id)sender
{
    int idx = (int)(((UIButton *)sender).tag - kPlayButtonTagKey);
    
    NSDictionary *downloadInfo = [downloadInfos objectAtIndex:idx];
    NSString* fileName = [downloadInfo objectForKey:@"name"];
    
    NSLog(@"fileName:%@", fileName);
    
    if ( [((UIButton *)sender).titleLabel.text isEqual:@"Play"] )
    {
        if( [FileCenter IsFileExistInDocuments:kStorePath fileName:fileName] )
        {
            [((UIButton *)sender) setTitle:@"Stop" forState:UIControlStateNormal];
            [self doStop];
            [self doPlay:idx];
        }
    }
    else if ( [((UIButton *)sender).titleLabel.text isEqual:@"Stop"] )
    {
        [((UIButton *)sender) setTitle:@"Play" forState:UIControlStateNormal];
        [self doStop];
    }
}

#pragma mark -- select row
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //NSLog(@"on selected %@", indexPath);
}

@end
